<template>
    <div class="app-container">
      <el-form :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules">
        <el-form-item label="试卷Id:"  prop="paperId" required>
          <el-input v-model="form.paperId" />
        </el-form-item>
        <el-form-item label="试卷名称:"  prop="paperName" required>
          <el-input v-model="form.paperName" placeholder="请输入试卷名称"/>
        </el-form-item>
        <el-form-item :key="index" :label="'大题'+(index+1)+'：'" required v-for="(titleItem,index) in titleItems2">
          <el-input v-model="titleItem.questionName" style="width: 80%" placeholder="请输入大题名"/>
          <!-- <el-select v-model="titleItem.questionName" @change="selectsubjectId" placeholder="大题选择">
            <el-option v-for="item in titleItemName" :key="item.ket" :value="item.key" :label="item.value"></el-option>
          </el-select> -->
          <el-button type="text" class="link-left" style="margin-left: 20px" size="mini" @click="addQuestion(titleItem)">
            添加试题
          </el-button>
          <!-- 修改了大题不能删除的bug -->
          <el-button type="text" class="link-left" size="mini" @click="titleItems2.splice(index,1)">删除</el-button>
          <el-card class="exampaper-item-box" v-if="titleItem.questionItems.length!==0">
            <el-form-item :key="questionIndex" :label="'题目'+(questionIndex+1)+'：'"
                          v-for="(questionItem,questionIndex) in titleItem.questionItems" style="margin-bottom: 15px">
              <el-row>
                        <!-- <el-input ></el-input>  questionItems-->
                <el-col :span="23">
                  <QuestionShow :qType="questionItem.type" :question="questionItem"/>
                </el-col>
                <el-col :span="1">
                  <el-button type="text" size="mini" @click="titleItem.questionItems.splice(questionIndex,1)">删除
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-card>
        </el-form-item>
        <!-- <el-form-item label="建议时长：" prop="suggestTime" required>
          <el-input v-model="form.suggestTime" placeholder="分钟"/>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">修改</el-button>
          <el-button type="success" @click="addTitle">添加大题</el-button>
        </el-form-item>
      </el-form>
  
      <el-dialog :visible.sync="questionPage.showDialog"  width="70%">
        <el-form :model="questionPage.queryParam" :inline="true">
          <el-form-item label="ID：">
            <el-input v-model="questionPage.queryParam.id" ref ="questionId" clearable></el-input>
          </el-form-item>
          <el-button type="primary" @click="queryForm">查询</el-button>
          &nbsp;
          <el-form-item label="题型：">
            <el-select v-model="questionPage.queryParam.type" @change="selecttype" clearable>
              <el-option v-for="item in questionTypeEnum" :key="item.key" :value="item.key" :label="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
                      <el-button type="primary" @click="RamdomSelectQuestion">随机出题</el-button>
  
          </el-form-item>
        </el-form>
        <el-table :data="questionPage.tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                  @selection-change="handleSelectionChange" border fit highlight-current-row style="width: 100%">
                  <!-- 宽度不够显示有... -->
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="questionId" label="Id" width="60px"/>
          <el-table-column prop="type" label="题型"  show-overflow-tooltip/>
          <el-table-column prop="questionName" label="题干" width="70px" />
          <el-table-column prop="answer" label="答案" width="70px"/>
          <el-table-column prop="score" label="分数" width="70px"/>
          <el-table-column label="操作" align="center" width="220px">
          <template slot-scope="{row}">
            <el-button size="mini"   @click="showQuestion(row)">预览</el-button>
          </template>
        </el-table-column>
        </el-table>
        <el-pagination align='center' @size-change="handleSizeChange" @current-change="handleCurrentChange" 
              :current-page="currentPage" 
              :page-sizes="[2,5,10,20]" 
              :page-size="pageSize" 
              layout="total, sizes, prev, pager, next, jumper" 
              :total="questionPage.tableData.length">
              </el-pagination>
        <!-- <pagination v-show="questionPage.total>0" :total="questionPage.total"
                    :page.sync="questionPage.queryParam.pageIndex" :limit.sync="questionPage.queryParam.pageSize"
                    @pagination="search"/> -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="questionPage.showDialog = false">取 消</el-button>
            <el-button type="primary" @click="confirmQuestionSelect">确定</el-button>
       </span>
      </el-dialog>
  
  
      <el-dialog :visible.sync="questionShow.dialog" style="width: 100%;height: 100%">
        <QuestionShow :qType="questionShow.qType" :question="questionShow.question" :qLoading="questionShow.loading"/>
      </el-dialog>
    </div>
  </template>
  
  <script>
  
  import { mapGetters, mapState, mapActions } from 'vuex'
  import Pagination from '@/components/Pagination'
  import QuestionShow from '@/components/Show'
  import examPaperApi from '@/api/examPaper'
  import questionApi from '@/api/question'
  import { onMounted } from 'vue'
  import { form } from '@/Utils/request copy'
  
  export default {
    components: { Pagination, QuestionShow },
    data () {
      return {
        idList:[],
              questionItems: [ ],
      addDialogVisible: false ,// 对话框显示
       titleItems2:[],
       addForm:[],
       addFormRules:[],
       addForm:{
          id: null,
          grade:null,
          courseId: [],
          paperType: 1,
         // limitDateTime: [],
          paperName:null,
          suggestTime: null,
           titleItems: [ ],
       },
       questionPagetableData: [
        ],
        currentPage: 1, // 当前页码
        total: null, // 总条数
        pageSize: 2 // 每页的数据条数
        ,
        questionShow: {
          qType: 1,
          dialog: false,
          question: null,
          loading: false
        },
        form: {
          id: null,
          level: null,
          courseId: null,
          paperType: 1,
         // limitDateTime: [],
          name:null,
          suggestTime: null,
           titleItems: 
           [
              
  
          ]
        },
        
        subjectFilter: [       
        //   { key :'1',value:'语文'},
        // { key :'2',value:'数学'},
        // { key :'3',value:'英语'},
        // { key :'4',value:'java'},
        // { key :'5',value:'c++'},
      ],
        formLoading: false,
        levelEnum:[   
      {
          key :'1',value:'一年级'},
        { key :'2',value:'二年级'},
        { key :'3',value:'三年级'},
        { key :'4',value:'四年级'},
        { key :'5',value:'大学年级'},
        ],
      //   titleItemName:[
      //   { key :'1',value:'单选题'},
      //   { key :'2',value:'多选题'},
      //   { key :'3',value:'判断题'},
      //   { key :'4',value:'问答题'},
      //  ],
        paperTypeEnum:[      
          { key :'1',value:'语文'},
        { key :'2',value:'数学'},
        { key :'3',value:'英语'},
        { key :'4',value:'java'},
        { key :'5',value:'c++'},],
     
        rules: {
          level: [
            { required: false, message: '请选择年级', trigger: 'change' }
          ],
          courseId: [
            { required: false, message: '请选择学科', trigger: 'change' }
          ],
          paperType: [
            { required: false, message: '请选择试卷类型', trigger: 'change' }
          ],
          name: [
            { required: false, message: '请输入试卷名称', trigger: 'blur' }
          ],
          suggestTime: [
            { required: false, message: '请输入建议时长', trigger: 'blur' }
          ]
        },
  
        questionPage: {
          //        this.questionPage.tableData = re.list
          // this.questionPage.total = re.total
          // this.questionPage.queryParam.pageIndex = re.pageNum
          // this.questionPage.listLoading = false
  
  
  
          multipleSelection: [
  
          ],
          showDialog: false,
          queryParam: {
            id: null,
            questionType: [ 
         { key :'1',value:'语文'},
        { key :'2',value:'数学'},
        { key :'3',value:'英语'},
        { key :'4',value:'java'},
        { key :'5',value:'c++'},
         ],
            type: null,
            courseId: '',
            pageIndex: 1,
            pageSize: 5
          },
          listLoading: true,
          tableData: [ ],
          total: 0
        },
        currentTitleItem:[
  
        ]
      }
    },
    created () {
  if(typeof this.$route.query.id !== 'undefined'){
        let id = this.$route.query.id
      console.log('当前的titleItems'+this.form.titleItems)
      console.log('传进来的id :' +id)
      this.$http.post("/get/paper?id="+id).then(
      re=>{
               this.form=re.data
               console.log('当前的re data'+re.data.titleItems)
               this.titleItems2 = re.data.titleItems
         }
       );  
      //     this.$http.post("paper/getTitleItems?id="+id).then(
      // res=>{
      //          this.titleItems2=res.data
      //         //  console.log('当前的titleItems'+this.form.titleItems)
      //           console.log('当前的res.data.titleItems :'+res)
  
      //    }
      //  ); 
     
  }
    },
    mounted(){
        this.getcourseId();
      },
    methods: {
          //每页条数改变时触发 选择一页显示多少行
          handleSizeChange(val) {
                      console.log(`每页 ${val} 条`);
                      this.currentPage = 1;
                      this.pageSize = val;
                  },
                  //当前页改变时触发 跳转其他页
                  handleCurrentChange(val) {
                      console.log(`当前页: ${val}`);
                      this.currentPage = val;
                  },
                  //将选择中的课程id赋值给form中的courseId
      selectsubjectId(value){
        this.form.courseId = value 
        // alert(value)
        // alert(this.form.courseId)
      },
      showQuestion (row) {
        let _this = this
        this.questionShow.dialog = true
        this.questionShow.loading = true
  
        this.$http.get("question/id?id="+row.questionId).then(
          re=>{
          
          _this.questionShow.qType = re.data.type
  
          _this.questionShow.question = re.data
          _this.questionShow.loading = false
              console.log("question :"+_this.questionShow.question.items)
              console.log("type :"+re.data.questionType)
  
              console.log("type :"+_this.questionShow.qType)
          })
  },
      async selecttype(value){//异常请求才能显示
        this.questionPage.tableData = [];
        var type = value
        var courseId = this.form.courseId
       const {data:res} =await this.$http.get("question/courseIdortype?courseId="+courseId+"&type="+type); 
  
      this.questionPage.listLoading = false
        if(res!=null){
          //  alert ("调用的结果"+res)
              this.questionPage.tableData = res
        }
        },
      async  submitForm () {
        this.$http.get("paper/delete/"+this.form.paperId).then(re => {
        // if (re.data != null) {
        //   this.$message.success(re.message)
        // } else {
        //   this.$message.error(re.message)
        // }
      })
          let _this = this
          this.$refs.form.validate(async(valid) => {
            if (valid) {
          this.form.titleItems=this.titleItems2
    
        const {data:re} =await  this.$http.post("edit/paper",this.form);  
         if(re!=null){
            this.$message.success("修改成功")
          }else{
            this.$message.error("修改失败")
          }
          } else {
            return false
          }
        })
        
      },
    async search () {
        // this.questionPage.queryParam.courseId = this.form.courseId
        //this.questionPage.listLoading = 
     // this.questionPage.tableData = questionPage.tableData
     var courseId = this.form.courseId
      // const {data:res} =await this.$http.get("question/courseIdortype?courseId="+courseId+"&type="+type);  
      const {data:res} =await this.$http.get("question/courseId?courseId="+courseId); 
  
     this.questionPage.listLoading = false
      if(courseId!=undefined){
        //  alert ("调用的结果"+res)
             this.questionPage.tableData = res
      }else{
        this.$message.error("您还没有选择考试科目")
      }
      },
      async queryForm () {
        this.questionPage.tableData = [];
        var questionId = this.$refs.questionId.value
        if(questionId == null){
        this.$message.error("您还没有输入试题编号")
        }
        const {data:res} = await this.$http.get("question/id?id="+questionId); 
        this.questionPage.listLoading = false
      if(res.questionName != null){
        //  alert ("调用的结果"+res)
             this.questionPage.tableData.push(res)
      }else if(res.questionId == null && questionId != null){
        this.$message.error("该试题不存在！！请重新输入")
      }
      },
      getcourseId(){
          this.$http.get("course/get").then(res =>{
            console.log("加载数据成功")
            this.subjectFilter=res.data;
            console.log(this.subjectFilter[1].courseId)
          })
        },
      addDialogClosed(){
        this.$refs.addFormRef.resetFields();// 重置表单项
      },
      addTitle () {
        
        this.titleItems2.push({
          questionName: '',
          // questionItems: []  //这是原来的
         questionItems:[
                    ]
        })
      },
      addQuestion (titleItem) {
        this.currentTitleItem = titleItem
        this.questionPage.showDialog = true
        this.search()
        // this.
      },
      removeTitleItem (titleItem) {
        this.titleItems.remove(titleItem)
      },
      removeQuestion (titleItem, questionItem) {
        titleItem.questionItems.remove(questionItem)
      },
      async RamdomSelectQuestion(){
           await this.$http.post("question/getQuestionIdList").then(
      re=>{
               this.idList=re.data
         }
     
  
       );  
  
       //mock一下数据好了  
   console.log('当前的re idList :'+this.idList.length)
          this.idList.forEach(id=>{
                      console.log("遍历")
            //以id为参数 遍历id   根据id查询到对应·的题目 然后放入questionItems当中 
       this.$http.post("question/getQuestionItems?id="+id).then(
           re=>{
               const res = re
               this.currentTitleItem.questionItems.push(res.data)
               }
       );  
  
          // if(re!=null){
          //    _this.currentTitleItem.questionItems.push(re)
          //  //  _this.form.titleItems.questionItems.push(re)
          // }
          })
             // alert(关闭窗口)
        this.questionPage.showDialog = false
      },
      confirmQuestionSelect () {
        let _this = this
         this.questionPage.multipleSelection.forEach (  q => {
            console.log("遍历")
            //以id为参数 遍历id   根据id查询到对应·的题目 然后放入questionItems当中 
       this.$http.post("question/id/?id="+q.questionId).then(
           re=>{
               const res = re
               _this.currentTitleItem.questionItems.push(res.data)
               }
       );  
  
          // if(re!=null){
          //    _this.currentTitleItem.questionItems.push(re)
          //  //  _this.form.titleItems.questionItems.push(re)
          // }
        
      
        })
  
     // alert(关闭窗口)
        this.questionPage.showDialog = false
     
      },
      levelChange () {
        this.form.courseId = null
        this.subjectFilter = this.subjects.filter(data => data.level === this.form.level)
      },
  
      handleSelectionChange (val) {
        this.questionPage.multipleSelection = val
        console.log('val'+val)
      },
      questionTypeFormatter (row, column, cellValue, index) {
        return this.enumFormat(this.questionTypeEnum, cellValue)
      },
      subjectFormatter (row, column, cellValue, index) {
        return this.subjectEnumFormat(cellValue)
      },
      resetForm () {
        let lastId = this.form.id
        this.$refs['form'].resetFields()
        this.form = {
          id: null,
          level: null,
          courseId: null,
          paperType: 1,
          limitDateTime: [],
          name: '',
          suggestTime: null,
          titleItems: []
        }
        this.form.id = lastId
      },
  
      ...mapActions('exam', { initSubject: 'initSubject' }),
      ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
    },
    computed: {
      ...mapGetters('enumItem', ['enumFormat']),
      ...mapState('enumItem', {
        questionTypeEnum: state => state.exam.question.typeEnum,
        paperTypeEnum: state => state.exam.examPaper.paperTypeEnum,
        levelEnum: state => state.user.levelEnum
      }),
      ...mapState('exam', { subjects: state => state.subjects })
    }
  }
  </script>
  
  <style lang="less">
    .exampaper-item-box {
      .q-title {
        margin: 0px 5px 0px 5px;
      }
     
    }
  </style>